package com.akn.mvvmlibrary.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.akn.mvvmlibrary.factory.AppViewModelFactory
import com.akn.mvvmlibrary.viewmodel.BaseViewModel

abstract class BaseFragment<VDB : ViewDataBinding, VM : BaseViewModel> : Fragment() {

    lateinit var binding: VDB

    lateinit var viewModel: VM

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val vm = createViewModel()
        viewModel = ViewModelProvider(
            this,
            AppViewModelFactory(vm)
        ).get(vm::class.java)
        binding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
        binding.setVariable(variableId(), viewModel)

        initView()

        return binding.root
    }


    /*子类实现，返回一个布局id*/
    abstract fun getLayoutId(): Int

    abstract fun initView()

    /*子类实现，返回一个viewModel*/
    abstract fun createViewModel(): VM

    /*需要绑定的viewModel的BR.id*/
    abstract fun variableId(): Int


}